package middleware

import (
	"github.com/zeromicro/go-zero/rest/httpx"
	"jingdong_product/api/internal/types"
	"jingdong_product/pkg"
	"net/http"
)

type UserAgentMiddleware struct {
}

func NewUserAgentMiddleware() *UserAgentMiddleware {
	return &UserAgentMiddleware{}
}

func (m *UserAgentMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		token := r.Header.Get("token")
		if token == "" {
			resp := &types.Response{
				Message: "token 未登录",
				Data:    nil,
				Code:    500,
			}
			httpx.OkJsonCtx(r.Context(), w, resp)
			return
		}
		//解析代码
		getToken, s := pkg.GetToken(token)
		if s != "" {
			resp := &types.Response{
				Message: s,
				Data:    nil,
				Code:    500,
			}
			httpx.OkJsonCtx(r.Context(), w, resp)
			return
		}
		r.ParseForm()
		r.Form.Set("userId", getToken["userId"].(string))
		next(w, r)
	}
}
